package com.sys.gradepaysys.controller.stuServlet;

import com.alibaba.fastjson.JSON;
import com.sys.gradepaysys.entity.Admin;
import com.sys.gradepaysys.entity.ResultData;
import com.sys.gradepaysys.entity.Student;
import com.sys.gradepaysys.service.AdminService;
import com.sys.gradepaysys.service.AdminServiceImpl;
import com.sys.gradepaysys.service.StudentService;
import com.sys.gradepaysys.service.StudentServiceImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "loginServlet", value = "/login")
public class loginServlet extends HttpServlet {
    private StudentService studentService=new StudentServiceImpl();
    private AdminService adminService=new AdminServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String admin=request.getParameter("admin");
        Student student=new Student();
        String s="";
        if (admin.equals("stu")){
            try {
                student = studentService.login(username, password);
                s = JSON.toJSONString(new ResultData<>(201,"登陆成功!",student));
                request.getSession().setAttribute("stu",student);
            } catch (Exception e) {
                s = JSON.toJSONString(new ResultData<>(500,e.getMessage(),null));
            }
        }
        if ( admin.equals("admin")){
            try {
                Admin admin1 = adminService.login(username, password);
                s = JSON.toJSONString(new ResultData<>(202,"登陆成功!",admin1));
            } catch (Exception e) {
                s = JSON.toJSONString(new ResultData<>(500,e.getMessage(),null));
            }
        }
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(s);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     doGet(request, response);
    }
}
